package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.constant.MessageConstant;
import com.itheima.dao.SubscribeDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.entity.Result;
import com.itheima.pojo.*;
import com.itheima.service.SubscribeService;
import com.itheima.utils.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service(interfaceClass = SubscribeService.class)
@Transactional
public class SubscribeServiceImpl implements SubscribeService {
    @Autowired
    private SubscribeDao subscribeDao;

    @Override
    public PageResult pageQuery(QueryPageBean queryPageBean) throws Exception {
        Integer currentPage = queryPageBean.getCurrentPage();
        Integer pageSize = queryPageBean.getPageSize();
        System.out.println(queryPageBean.getOrderStatus());


        if (queryPageBean.getStarttime() != null && !queryPageBean.getStarttime().equals("") || queryPageBean.getEndtime() != null && !queryPageBean.getEndtime().equals("")) {
            /*开始时间*/
            Date orderDate = DateUtils.parseString2Date(queryPageBean.getStarttime());
            long Start = orderDate.getTime() + 24 * 60 * 60 * 1000;
            Date date = new Date(Start);
            String Starttime = new SimpleDateFormat("yyyy-MM-dd").format(date);

            //结束时间
            Date end = DateUtils.parseString2Date(queryPageBean.getEndtime());
            long enddate = end.getTime() + 24 * 60 * 60 * 1000;
            Date date2 = new Date(enddate);
            String endtime = new SimpleDateFormat("yyyy-MM-dd").format(date2);

            queryPageBean.setStarttime(Starttime);
            queryPageBean.setEndtime(endtime);
        }

        PageHelper.startPage(currentPage, pageSize);
        Page<subscribe> page = subscribeDao.findByCondition(queryPageBean);
        return new PageResult(page.getTotal(), page.getResult());
    }


    @Override
    public List<Setmeal> echoSetmeal() {
        return subscribeDao.echoSetmeal();
    }

    /*编辑框基本信息回显*/
    @Override
    public Map editecho(Map row) {
        Map editechobasic = subscribeDao.editechobasic(row);
        return editechobasic;

    }

    //回显套餐id
    public Integer[] setmealecho(Map row) {
        return subscribeDao.setmealecho(row);
    }

    /*编辑*/
    @Override
    public Result editor(Map map, Integer[] id) throws Exception {
        if (id.length != 1) {
            return new Result(false, "请选择一个套餐");
        }
        Integer memberId = (Integer) map.get("memberId");
        Member member = subscribeDao.findmemberId(memberId);
        String name = (String) map.get("name");
        //更新会员名称
        subscribeDao.editorMem(member.getId(), name);
        String s=(String) map.get("orderDate");
        char c = s.charAt(10);
        long time;
        if (c==' '){
            Date orderDate = DateUtils.parseString2Date((String) map.get("orderDate"));
            time = orderDate.getTime();
        }else {
            Date orderDate = DateUtils.parseString2Date((String) map.get("orderDate"));
            time = orderDate.getTime()+24 * 60 * 60 * 1000;
        }
        String timestr = new Date(time).toLocaleString();
        Date orderDatew = DateUtils.parseString2Date(timestr);
        String format = new SimpleDateFormat("yyyy-MM-dd").format(orderDatew);

        map.put("orderDate", format);
        /*当前日期可否预约*/
        OrderSetting oderSet = subscribeDao.todayOrderFill(format);
        if (oderSet == null) {
            //今日不可用预约
            return new Result(false, MessageConstant.SELECTED_DATE_CANNOT_ORDER);
        }
        /*修改预约详情（基本信息）*/
        subscribeDao.editorOder(map);
        /*清楚预约表和套餐id的关联*/
        subscribeDao.eliminateSetmealId(map);

        /*修改套餐信息*/
        for (Integer ids : id) {    //数组只会有一个id
            subscribeDao.editorSetmeal(map, ids);
        }
        return new Result(true, "预约编辑成功");
    }

    /*删除根据谁删除啊*/
    @Override
    public void dele(Map row) {
        //判断是否在详情、地址表
        long i = subscribeDao.isOrderAddz(row);
        if (i >= 0) {
            //删除中间表
            subscribeDao.deleOderandAddr(row);
        }
        subscribeDao.delebasic(row);
    }

    //按钮改状态
    @Override
    public void alterthestate(Map state) {
        subscribeDao.alterthestate(state);
    }

    //新增预约
    @Override
    public Result addoder(Map formData, Integer[] ids) throws Exception {
        //判断用户有没有选择套餐
        if (ids.length == 0) {
            return new Result(false, "请选择套餐");
        }
        String orderDates = (String) formData.get("orderDate");
        if (orderDates == null) {
            return new Result(false, "请选择日期");
        }
        Date orderDate = DateUtils.parseString2Date(orderDates);
        long time = orderDate.getTime() + 24 * 60 * 60 * 1000;
        Date date2 = new Date(time);
        String format = new SimpleDateFormat("yyyy-MM-dd").format(date2);
        String phoneNumber = (String) formData.get("phoneNumber");
        String name = (String) formData.get("name");

        //判断当前日期是否可以预约
        OrderSetting oderSet = subscribeDao.todayOrderFill(format);
        if (oderSet == null) {
            //今日不可用预约
            return new Result(false, MessageConstant.SELECTED_DATE_CANNOT_ORDER);
        }
        //判断预约满了吗
        if (oderSet.getReservations() >= oderSet.getNumber()) {
            //说明人数满了
            return new Result(false, MessageConstant.ORDER_FULL);
        }
        //根据用户传入的信息，首先判断是否存在，
        Member member = subscribeDao.ismember(phoneNumber, name);
        if (member == null) {
            return new Result(false, "没有会员信息请注册");
        }
        //判断套餐去重
        //查询预约详情
        for (Integer id : ids) {
            List<Order> orderdb = subscribeDao.findOder(format, id, member.getId());  //套餐id，会员id，日期
            System.out.println(orderdb != null);
            System.out.println(orderdb.size() > 0);
            if (orderdb.size() > 0) {
                Result result = new Result(false, MessageConstant.HAS_ORDERED);     //重复预约
                return result;
            } else {
                //都符合了就添加预约详情
                Order order = new Order();
                order.setMemberId(member.getId());
                order.setOrderDate(date2);
                order.setOrderType("电话预约");
                order.setOrderStatus("未到诊");
                order.setSetmealId(id);
                subscribeDao.addoder(order);
                //生成了预约详情那么要添加已预约人数
                subscribeDao.reservations(date2);
            }
        }
        //还需要将套餐id集进行添加  ， 需要先回显套餐信息
        return new Result(true, MessageConstant.ORDER_SUCCESS);
    }
}
